import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:series_play/comm/base/user_manager.dart';

class HeaderInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final token = await UserManager.getToken();
    if (token.isNotEmpty) {
      options.headers['Authorization'] = token;
    }

    final params = {'language': 'zh'};

    if (options.data is Map) {
      // data 是 map
      options.data = {...options.data, ...params};
    } else if (options.data is FormData) {
      // data 是 FormData
      final formData = options.data as FormData;
      formData.fields.addAll(
        params.entries.map((e) => MapEntry(e.key, e.value.toString())),
      );
    } else if (options.data is String) {
      // data 是 JSON 字符串
      Map<String, dynamic> dataMap = {};
      try {
        dataMap = jsonDecode(options.data);
      } catch (_) {}
      dataMap.addAll(params);
      options.data = jsonEncode(dataMap);
    }


    handler.next(options);
  }
}
